<template>
  <div class="user-add-container">
    <div class="page-header">
      <div class="header-title">
        <h2>{{ isEdit ? '编辑用户' : '添加用户' }}</h2>
        <span class="subtitle">{{ isEdit ? '修改用户信息' : '创建新的系统用户' }}</span>
      </div>
      <div class="header-actions">
        <el-button @click="goBack">返回</el-button>
      </div>
    </div>

    <el-card class="form-container" shadow="hover">
      <el-form
        :model="userForm"
        :rules="userRules"
        ref="userFormRef"
        label-width="120px"
        :disabled="loading"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" :disabled="isEdit" placeholder="请输入用户名" />
        </el-form-item>
        
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input v-model="userForm.password" type="password" show-password placeholder="请输入密码" />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword" v-if="!isEdit">
          <el-input v-model="userForm.confirmPassword" type="password" show-password placeholder="请再次输入密码" />
        </el-form-item>
        
        <el-form-item label="姓名" prop="fullName">
          <el-input v-model="userForm.fullName" placeholder="请输入姓名" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="userForm.phoneNumber" placeholder="请输入手机号" />
        </el-form-item>
        
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择角色">
            <el-option label="超级管理员" value="ROLE_ADMIN" />
            <el-option label="小区管理员" value="ROLE_MANAGER" />
            <el-option label="业主" value="ROLE_OWNER" />
            <el-option label="普通员工" value="ROLE_STAFF" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">保存</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import axios from 'axios';

const route = useRoute();
const router = useRouter();
const loading = ref(false);
const userFormRef = ref(null);

// 判断是否为编辑模式
const isEdit = computed(() => {
  return route.query.id !== undefined;
});

// 用户表单数据
const userForm = reactive({
  id: null,
  username: '',
  password: '',
  confirmPassword: '',
  fullName: '',
  email: '',
  phoneNumber: '',
  role: ''
});

// 表单验证规则
const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'));
  } else {
    if (userForm.confirmPassword !== '') {
      // 对第二个密码框单独验证
      userFormRef.value.validateField('confirmPassword');
    }
    callback();
  }
};

const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'));
  } else if (value !== userForm.password) {
    callback(new Error('两次输入密码不一致!'));
  } else {
    callback();
  }
};

const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { validator: validatePass, trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validatePass2, trigger: 'blur' }
  ],
  fullName: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
};

// 初始化
onMounted(async () => {
  if (isEdit.value) {
    await fetchUserData();
  }
});

// 获取用户数据
const fetchUserData = async () => {
  const userId = route.query.id;
  if (!userId) return;
  
  loading.value = true;
  try {
    const token = localStorage.getItem('token');
    const response = await axios.get(`/api/users/${userId}`, {
      headers: { Authorization: `Bearer ${token}` }
    });
    
    // 填充表单
    const userData = response.data;
    userForm.id = userData.id;
    userForm.username = userData.username;
    userForm.fullName = userData.fullName || '';
    userForm.email = userData.email || '';
    userForm.phoneNumber = userData.phoneNumber || '';
    userForm.role = userData.role || '';
  } catch (error) {
    console.error('获取用户数据失败:', error);
    ElMessage.error('获取用户数据失败');
    goBack();
  } finally {
    loading.value = false;
  }
};

// 提交表单
const submitForm = async () => {
  if (!userFormRef.value) return;
  
  await userFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    loading.value = true;
    try {
      const token = localStorage.getItem('token');
      const headers = { Authorization: `Bearer ${token}` };
      
      // 准备提交的数据
      const submitData = { ...userForm };
      delete submitData.confirmPassword;
      
      if (isEdit.value) {
        // 编辑模式下不提交密码
        delete submitData.password;
        
        // 更新用户
        await axios.put(`/api/users/${userForm.id}`, submitData, { headers });
        ElMessage.success('用户更新成功');
      } else {
        // 创建用户
        await axios.post('/api/users', submitData, { headers });
        ElMessage.success('用户创建成功');
      }
      
      // 返回列表页
      goBack();
    } catch (error) {
      console.error('保存用户失败:', error);
      ElMessage.error('保存用户失败: ' + (error.response?.data?.message || error.message));
    } finally {
      loading.value = false;
    }
  });
};

// 重置表单
const resetForm = () => {
  userFormRef.value?.resetFields();
};

// 返回列表页
const goBack = () => {
  router.push('/system/user');
};
</script>

<style scoped>
.user-add-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title {
  display: flex;
  flex-direction: column;
}

.header-title h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.subtitle {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.form-container {
  max-width: 800px;
  margin: 0 auto;
}

.form-container .el-form {
  padding: 20px 0;
}
</style> 